package com.want.evenchat.controller.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

import com.want.evenchat.R;
import com.want.evenchat.model.bean.PickContactInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Want on 2018/5/8.
 */

//选择联系人的页面的页面适配器
public class PickContactAdapter extends BaseAdapter{

    private Context mContext;

    private List<PickContactInfo> mPicks = new ArrayList<>();

    private List<String> mExitsMembers = new ArrayList<>();//保存群中存在的成员集合

    public PickContactAdapter(Context context , List<PickContactInfo> picks , List<String> exitMembers) {
        mContext = context;

        if (mPicks != null && mPicks.size() >= 0){
            mPicks.clear();
            mPicks.addAll(picks);
        }

        //加载已存在的成员集合
        mExitsMembers.clear();
        mExitsMembers.addAll(exitMembers);
    }

    @Override
    public int getCount() {
        return mPicks == null ? 0:mPicks.size();
    }

    @Override
    public Object getItem(int position) {
        return mPicks.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        //创建或获取ViewHolder
        ViewHolder holder = null;

        if (convertView == null){
            holder = new ViewHolder();

            convertView = View.inflate(mContext , R.layout.item_pick , null);

            holder.check_pick = convertView.findViewById(R.id.check_pick);
            holder.textview_pick_name = convertView.findViewById(R.id.textview_pick_name);

            convertView.setTag(holder);

        }else {
            holder = (ViewHolder) convertView.getTag();
        }

        //获取当前Item数据
        PickContactInfo pickContactInfo = mPicks.get(position);

        //显示数据
        holder.textview_pick_name.setText(pickContactInfo.getUser().getName());
        holder.check_pick.setChecked(pickContactInfo.ismIsChecked());

        //判断
        if (mExitsMembers.contains(pickContactInfo.getUser().getHxid())){
            holder.check_pick.setChecked(true);
            pickContactInfo.setmIsChecked(true);
        }

        //返回数据
        return convertView;
    }

    //获取选择的联系人
    public List<String> getPickContacts() {

        List<String> picks = new ArrayList<>();

        for(PickContactInfo pick : mPicks){
            //判断是否选中
            if (pick.ismIsChecked()){
                picks.add(pick.getUser().getName());
            }
        }
        return picks;
    }

    private class ViewHolder{
        private CheckBox check_pick;
        private TextView textview_pick_name;
    }
}
